package guet.imagan.progbuilder.annotation;

import guet.imagan.progbuilder.Compiler;
import guet.imagan.progbuilder.Interpreter;
import guet.imagan.util.ListUtil;

import java.util.List;

/**
 * 对本包下的注解进行处理的工具
 */
public class AnnotationTool {

	/**
	 * 根据编译器类名，创建并返回一个具体的编译器对象,若该类名对应的类不是直接或间接继承Compiler类，且没有加CompileCommand注解
	 * 则返回null
	 */
	public static Compiler getCompiler(Class<?> clazz) throws Exception {
		Compiler c;
		try {
			c = (Compiler) clazz.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			return null;
		}
		CompileCommand compileCmd = clazz.getAnnotation(CompileCommand.class);
		if (compileCmd == null) return null;
		List<String> cmd = ListUtil.array2List(compileCmd.command());
		c.setCommand(cmd);
		c.setCompilerName(compileCmd.commpilerName());
		List<String> srcExt = ListUtil.array2List(compileCmd.sourceFileExtension());
		c.setSrcFileExt(srcExt);
		c.setTargeFileExt(compileCmd.targetFileExtension());
		return c;
	}


	public static Interpreter getInterpreter(Class<?> clazz) throws Exception {
		Interpreter c;
		try {
			c = (Interpreter) clazz.newInstance();
		} catch (InstantiationException e) {
			throw new Exception("解释器对象初始化失败");
		} catch (IllegalAccessException e) {
			throw new Exception("非法访问异常");
		}
		InterpreteCommand interpreteCommand = clazz.getAnnotation(InterpreteCommand.class);
		if (interpreteCommand == null) throw new Exception("该类未加注解");
		List<String> cmd = ListUtil.array2List(interpreteCommand.commandWithoutWindow());
		c.setCommandWithoutWindow(cmd);
		List<String> cmd1 = ListUtil.array2List(interpreteCommand.commandWithWindow());
		c.setCommandWithWindow(cmd1);
		c.setInterpreterName(interpreteCommand.interpreterName());
		List<String> srcExt = ListUtil.array2List(interpreteCommand.FileExtension());
		c.setSrcFileExt(srcExt);

		return c;
	}

	/**
	 * 返回一个类名对应的Compiler对象，若该类名不能转换为Compiler对象，则返回null
	 * @param className
	 * @return
	 * @throws Exception
	 */
	public static Compiler getCompiler(String className) throws Exception {
		Class<?> clazz = Class.forName(className);
		return getCompiler(clazz);
	}

	public static Interpreter getInterpreter(String className) throws Exception {
		Class<?> clazz = Class.forName(className);
		return getInterpreter(clazz);
	}

}
